package com.xd.clap.utils;

import com.xd.clap.commons.Const;
import com.xd.clap.entity.response.Result;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


public class SaveImage {
    @SneakyThrows
    public static Result saveImage(MultipartFile file) {
        //判断文件是否为空
        if (file == null) {
            return Result.fail(100, "请选择要上传的图片");
        }
        //判断文件大小
        if (file.getSize() > 1024 * 1024 * 15) {
            return Result.fail(100, "文件大小不能超过15M");
        }
        //获取文件后缀
        String oldName = file.getOriginalFilename();
        assert oldName != null;
        String suffix = oldName.substring(oldName.lastIndexOf(".") + 1);
        //判断文件格式
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return Result.fail(100, "请选择jpg,jpeg,gif,png格式的图片");
        }
        //生成新的名字
        String newName = UUID.randomUUID() + "." + suffix;
        InputStream inputStream = file.getInputStream();
        //创建时间文件夹
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        date = "File/" + date;
        Path directoryDay = Paths.get(date);
        if (!Files.exists(directoryDay)) {
            Files.createDirectories(directoryDay);
        }
        //保存文件
        Files.copy(inputStream, directoryDay.resolve(newName));
        //返回文件路径
        String fileDownloadUrl;
        if (Const.IS_DEBUG) {
            fileDownloadUrl = Const.BASE_URL + date + "/" + newName;
        } else {
            fileDownloadUrl = Const.SERVER_URl + date + "/" + newName;
        }
        return Result.success(fileDownloadUrl, "上传成功!");
    }
}
